package com.example.threadLocalLearning;

public class TL3 {

    /**
     * 使用 `withInitial()` 方法为 `ThreadLocal` 设置初始值。
     * 1. `withInitial()` 方法设置了初始值。
     * 2. 每个线程获取的初始值是独立的。
     * 3. 线程对 `ThreadLocal` 值的修改互不干扰。
     */
    private static final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Initial Value:" + threadLocal.get());
            threadLocal.set(threadLocal.get() + 10);
            System.out.println(Thread.currentThread().getName() + "Current Value:" + threadLocal.get());
        });

        Thread t2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Initial Value:" + threadLocal.get());
            threadLocal.set(threadLocal.get() + 20);
            System.out.println(Thread.currentThread().getName() + "Current Value:" + threadLocal.get());
        });

        t1.start();
        t2.start();

    }

}
